package com.avic.controller;

import com.avic.common.constant.SystemLogConstant;
import com.avic.common.constant.UserConstant;
import com.avic.common.convertor.EmergencyResourceConvertor;
import com.avic.common.util.AssertUtil;
import com.avic.common.util.ex.BizErrorCode;
import com.avic.common.util.lang.BaseResponse;
import com.avic.common.util.lang.ServiceCallBack;
import com.avic.controller.request.CreateEmergencyResourceReq;
import com.avic.controller.request.GetEmergencyResourceListReq;
import com.avic.controller.request.UpdateEmergencyResourceReq;
import com.avic.controller.result.BaseCreateResourceRes;
import com.avic.controller.result.GetEmergencyResourceListRes;
import com.avic.controller.result.GetEmergencyResourceRes;
import com.avic.dal.condition.EmergencyResourceListCondition;
import com.avic.dal.model.EmergencyResource;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


@Slf4j
@RestController
@RequestMapping("resource/emergency")
@Api(tags = "应急资源", description = "应急资源")
public class EmergencyResourceController extends AbstractFacadeImpl {

    @ApiOperation(value = "分页查询应急资源列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "requestBody", required = true, dataType = "GetEmergencyResourceListReq")
    })
    @PostMapping("list")
    public GetEmergencyResourceListRes getEmergencyResource(@RequestBody GetEmergencyResourceListReq requestBody) {
        final GetEmergencyResourceListRes result = new GetEmergencyResourceListRes();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {
            }

            @Override
            public void doService() throws Exception {
                EmergencyResourceListCondition emergencyResourceListCondition = new EmergencyResourceListCondition(
                        requestBody.getCurrentPage(), requestBody.getPageSize()
                );
                emergencyResourceListCondition.setResourceNumber(requestBody.getResourceNumber());
                emergencyResourceListCondition.setResourceType(requestBody.getResourceType());

                List<EmergencyResource> emergencyResources = emergencyResourceService.emergencyResourceList(emergencyResourceListCondition);

                result.setItemList(EmergencyResourceConvertor.emergencyResourcesToEmergencyResourceInfo(emergencyResources));
                result.setItemTotal(emergencyResourceService.emergencyResourceListTotal(emergencyResourceListCondition));
                result.setSuccess(true);
            }
        });
    }

    @ApiOperation(value = "创建应急资源")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "requestBody", required = true, dataType = "CreateEmergencyResourceReq")
    })
    @PostMapping
    public BaseCreateResourceRes createEmergencyResource(@RequestBody CreateEmergencyResourceReq requestBody,
                                                         @RequestHeader(value = UserConstant.HEADER_CURRENT_USER_ID_KEY, required = false) String currentUserId) {
        final BaseCreateResourceRes result = new BaseCreateResourceRes();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {
                AssertUtil.isNotBlank(requestBody.getResourceNumber(), "资源编号不能为空");
                AssertUtil.isTrue(emergencyResourceService.emergencyNumberCount(
                        requestBody.getResourceNumber()) <= 0, BizErrorCode.PARAM_ERROR, "资源编号已经存在");

            }

            @Override
            public void doService() throws Exception {
                EmergencyResource emergencyResource = new EmergencyResource();
                emergencyResource.setResourceCount(requestBody.getResourceCount());
                emergencyResource.setResourceDept(requestBody.getResourceDept());
                emergencyResource.setResourceLeader(requestBody.getResourceLeader());
                emergencyResource.setResourceName(requestBody.getResourceName());
                emergencyResource.setResourceNumber(requestBody.getResourceNumber());
                emergencyResource.setResourceType(requestBody.getResourceType());
                emergencyResource.setResourcePurpose(requestBody.getResourcePurpose());
                result.setItemId(emergencyResourceService.createEmergencyResource(emergencyResource));

                // 新建系统日志
                systemServiceFeignService.createSystemLog(
                        String.format(SystemLogConstant.CREATE_EMERGENCY_RESOURCE, result.getItemId(),
                                objectMapper.writeValueAsString(requestBody)), currentUserId);
                result.setSuccess(true);
            }
        });
    }

    @ApiOperation(value = "通过ID获取资源数据详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "emergencyId", value = "资源ID", required = true, dataType = "path")
    })
    @GetMapping("/{emergencyId}")
    public GetEmergencyResourceRes getEmergencyResource(@PathVariable("emergencyId") String emergencyId) {
        final GetEmergencyResourceRes result = new GetEmergencyResourceRes();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {
                AssertUtil.isNotBlank(emergencyId, "资源编号不能为空");
            }

            @Override
            public void doService() throws Exception {
                result.setEmergencyResourceInfo(EmergencyResourceConvertor
                        .emergencyResourceToEmergencyResourceInfo(emergencyResourceService.queryEmergencyResourceById(emergencyId)));
                result.setSuccess(true);
            }
        });
    }


    @ApiOperation(value = "修改应急资源")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "requestBody", required = true, dataType = "UpdateEmergencyResourceReq")
    })
    @PutMapping
    public BaseResponse updateEmergencyResource(@RequestBody UpdateEmergencyResourceReq requestBody,
                                                @RequestHeader(value = UserConstant.HEADER_CURRENT_USER_ID_KEY, required = false) String currentUserId) {
        final BaseResponse result = new BaseResponse();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {
                AssertUtil.isNotBlank(requestBody.getId(), "ID 不能为空");
                AssertUtil.isNotBlank(requestBody.getResourceNumber(), "编号不能为空");

            }

            @Override
            public void doService() throws Exception {

                EmergencyResource emergencyResource = emergencyResourceService.queryEmergencyResourceById(requestBody.getId());
                AssertUtil.isTrue(null != emergencyResource, BizErrorCode.PARAM_ERROR, "资源数据不存在");
                if (!StringUtils.equals(emergencyResource.getResourceNumber(), requestBody.getResourceNumber())) {
                    AssertUtil.isTrue(emergencyResourceService.emergencyNumberCount(
                            requestBody.getResourceNumber()) <= 0, BizErrorCode.PARAM_ERROR, "资源编号已经存在");
                }
                EmergencyResource emergencyResourceDB = new EmergencyResource();
                emergencyResourceDB.setId(requestBody.getId());
                emergencyResourceDB.setResourceType(requestBody.getResourceType());
                emergencyResourceDB.setResourceNumber(requestBody.getResourceNumber());
                emergencyResourceDB.setResourceName(requestBody.getResourceName());
                emergencyResourceDB.setResourceLeader(requestBody.getResourceLeader());
                emergencyResourceDB.setResourceDept(requestBody.getResourceDept());
                emergencyResourceDB.setResourceCount(requestBody.getResourceCount());
                emergencyResourceDB.setResourcePurpose(requestBody.getResourcePurpose());

                emergencyResourceService.updateEmergencyResource(emergencyResourceDB);

                // 新建系统日志
                systemServiceFeignService.createSystemLog(
                        String.format(SystemLogConstant.UPDATE_EMERGENCY_RESOURCE, emergencyResourceDB.getId(),
                                objectMapper.writeValueAsString(requestBody)), currentUserId);

                result.setSuccess(true);
            }
        });
    }

    @ApiOperation(value = "删除应急资源")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "itemId", paramType = "path", value = "资源ID", required = true)
    })
    @DeleteMapping("/{itemId}")
    public BaseResponse deleteEmergencyResource(@PathVariable("itemId") String itemId,
                                                @RequestHeader(value = UserConstant.HEADER_CURRENT_USER_ID_KEY, required = false) String currentUserId) {
        final BaseResponse result = new BaseResponse();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {
                AssertUtil.isNotBlank(itemId, "资源ID不能为空");

            }

            @Override
            public void doService() throws Exception {

                emergencyResourceService.deleteEmergencyResource(itemId);

                // 新建系统日志
                systemServiceFeignService.createSystemLog(
                        String.format(SystemLogConstant.DELETE_EMERGENCY_RESOURCE, itemId), currentUserId);
                result.setSuccess(true);
            }
        });
    }
}
